package com.wjh.anyview.quartz.config;

import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.Executor;

/**
 * 调度器配置类
 *
 * @author wjh
 * @date 2021/10/22 1:21
 * @Package com.wjh.anyview.quartz.config
 */
@Configuration
public class SchedulerConfig {

    @Autowired
    private DataSource dataSource;

    @Bean
    public Scheduler scheduler() throws IOException {
        return schedulerFactoryBean().getScheduler();
    }

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
        SchedulerFactoryBean factoryBean = new SchedulerFactoryBean();
        //设置factoryBean的名称
        factoryBean.setSchedulerName("cluster_factory");
        //设置factoryBean的数据源
        factoryBean.setDataSource(dataSource);
        //设置factoryBean的key，名称为cluster_key
        factoryBean.setApplicationContextSchedulerContextKey("cluster_key");
        //读取配置文件
        factoryBean.setQuartzProperties(quartzProperties());
        //设置线程池
        factoryBean.setTaskExecutor(schedulerThreadPool());
        //0s后执行，及立即执行
        factoryBean.setStartupDelay(0);
        return factoryBean;
    }

    @Bean
    public Properties quartzProperties() throws IOException {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        //设置路径
        propertiesFactoryBean.setLocation(new ClassPathResource("/spring-quartz.properties"));
        //调用读取配置文件的api
        propertiesFactoryBean.afterPropertiesSet();
        return propertiesFactoryBean.getObject();
    }

    @Bean
    public Executor schedulerThreadPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //获取当前cpu的核数
        int num = Runtime.getRuntime().availableProcessors();
        //设置线程数
        executor.setCorePoolSize(num);
        //最大线程数
        executor.setMaxPoolSize(num);
        //设置等待队列容量
        executor.setQueueCapacity(num);
        return executor;
    }
}
